Popular Searches
Popular Course Categories
Popular Courses

File Upload

Advanced Selenium

<div class="selenium-notes">

<h1>File Upload in Selenium WebDriver</h1>

<p><strong>File Upload</strong> is a common browser automation requirement in Selenium testing. Many web applications provide file upload functionality for documents, images, resumes, profile pictures, reports, PDFs, CSV files, and other files.</p>

<p>Selenium WebDriver can automate file upload when the web application uses an HTML <strong>&lt;input type="file"&gt;</strong> element. The most common approach is to locate the file input element and use the <strong>sendKeys()</strong> method to provide the complete path of the file.</p>

<p>File upload automation is frequently used in Selenium test scenarios such as registration forms, job portals, document submission systems, profile management, e-commerce applications, support portals, and administrative applications.</p>

<p><strong>Course Resource:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is File Upload?</h2>

<p>File upload is the process of selecting a file from the local computer and submitting it to a web application through an upload control.</p>

<p>For example, an application may contain an upload field for selecting a profile image:</p>

<pre><code>&lt;input type="file" id="profileImage"&gt;</code></pre>

<p>In Selenium, this element can normally be located and supplied with a file path using <strong>sendKeys()</strong>.</p>

<hr>

<h2>2. Why is File Upload Important in Selenium?</h2>

<p>File upload is important because many real-world web applications require users to upload files during different workflows.</p>

<ul>

<li>Resume upload.</li>

<li>Profile picture upload.</li>

<li>Document submission.</li>

<li>PDF upload.</li>

<li>CSV or Excel upload.</li>

<li>Image upload.</li>

<li>Product image upload.</li>

<li>Identity document upload.</li>

<li>Support attachment upload.</li>

<li>Bulk data upload.</li>

<li>Importing configuration files.</li>

</ul>

<p>Automating these workflows allows testers to validate that file selection, validation, submission, and error handling work correctly.</p>

<hr>

<h2>3. Basic File Upload Flow</h2>

<p>The basic Selenium file upload process can be represented as:</p>

<pre><code>Open Application

        |

        v

Navigate to Upload Page

        |

        v

Locate &lt;input type="file"&gt;

        |

        v

Use sendKeys()

        |

        v

Provide Absolute File Path

        |

        v

File Selected

        |

        v

Click Upload / Submit

        |

        v

Validate Upload Result</code></pre>

<hr>

<h2>4. HTML File Upload Element</h2>

<p>Understanding the HTML structure is important before automating a file upload.</p>

<pre><code>&lt;label for="fileUpload"&gt;Choose File&lt;/label&gt;

&lt;input type="file" id="fileUpload"&gt;</code></pre>

<p>The important element is the <strong>input</strong> element with <strong>type="file"</strong>.</p>

<p>Selenium can interact directly with this element when it is available and accessible in the DOM.</p>

<hr>

<h2>5. Using sendKeys() for File Upload</h2>

<p>The most common Selenium approach is to locate the file input and use <strong>sendKeys()</strong> with the file path.</p>

<pre><code>WebElement upload = driver.findElement(By.id("fileUpload"));

upload.sendKeys("C:\\Users\\User\\Documents\\resume.pdf");</code></pre>

<p>Unlike normal text input, the value supplied to <strong>sendKeys()</strong> represents the local file path that should be selected for upload.</p>

<hr>

<h2>6. Complete Basic File Upload Example</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class FileUploadTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/upload");

 

        driver.findElement(By.id("fileUpload"))

                .sendKeys("C:\\Users\\User\\Documents\\resume.pdf");

 

        driver.findElement(By.id("uploadButton"))

                .click();

 

        driver.quit();

    }

}</code></pre>

<p>The script performs the following operations:</p>

<ol>

<li>Starts the browser.</li>

<li>Opens the upload page.</li>

<li>Locates the file input.</li>

<li>Provides the file path.</li>

<li>Clicks the upload button.</li>

<li>Closes the browser.</li>

</ol>

<hr>

<h2>7. File Upload Using ID Locator</h2>

<p>If the file input has a unique ID, the ID locator is a simple and readable approach.</p>

<pre><code>driver.findElement(By.id("fileUpload"))

        .sendKeys("C:\\TestData\\sample.pdf");</code></pre>

<p>ID locators are generally easy to maintain when the application provides stable IDs.</p>

<hr>

<h2>8. File Upload Using Name Locator</h2>

<p>If the upload element contains a unique name attribute, Selenium can locate it using <strong>By.name()</strong>.</p>

<pre><code>&lt;input type="file" name="documentUpload"&gt;</code></pre>

<pre><code>driver.findElement(By.name("documentUpload"))

        .sendKeys("C:\\TestData\\document.pdf");</code></pre>

<hr>

<h2>9. File Upload Using CSS Selector</h2>

<p>CSS selectors can be used when an appropriate ID or name locator is unavailable.</p>

<pre><code>driver.findElement(By.cssSelector("input[type='file']"))

        .sendKeys("C:\\TestData\\image.png");</code></pre>

<p>If multiple file inputs exist, a more specific CSS selector should be used.</p>

<pre><code>driver.findElement(

        By.cssSelector("input[type='file'][id='profileImage']")

).sendKeys("C:\\TestData\\profile.png");</code></pre>

<hr>

<h2>10. File Upload Using XPath</h2>

<p>XPath can also be used to identify a file input.</p>

<pre><code>driver.findElement(By.xpath("//input[@type='file']"))

        .sendKeys("C:\\TestData\\document.pdf");</code></pre>

<p>A more specific XPath can be used when several upload controls are present.</p>

<pre><code>driver.findElement(

        By.xpath("//input[@type='file' and @id='resume']")

).sendKeys("C:\\TestData\\resume.pdf");</code></pre>

<hr>

<h2>11. Absolute File Path</h2>

<p>An absolute file path specifies the complete location of a file on the computer.</p>

<pre><code>C:\Users\User\Documents\TestData\resume.pdf</code></pre>

<p>In Java strings, Windows backslashes need to be escaped.</p>

<pre><code>String filePath = "C:\\Users\\User\\Documents\\TestData\\resume.pdf";</code></pre>

<p>An absolute path is straightforward for local execution, but hard-coding machine-specific paths can reduce framework portability.</p>

<hr>

<h2>12. Relative File Path</h2>

<p>A relative path is specified relative to the project's working directory.</p>

<pre><code>test-data/resume.pdf</code></pre>

<p>Using project-relative test data can make an automation framework easier to share across different machines.</p>

<pre><code>String filePath = "test-data/resume.pdf";

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath);</code></pre>

<hr>

<h2>13. Using System.getProperty("user.dir")</h2>

<p>A common approach for creating a portable path is to obtain the current project directory using <strong>System.getProperty("user.dir")</strong>.</p>

<pre><code>String projectPath = System.getProperty("user.dir");

 

String filePath = projectPath

        + "\\test-data\\resume.pdf";

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath);</code></pre>

<p>This avoids depending directly on a specific user's home directory.</p>

<hr>

<h2>14. File Upload with Path</h2>

<p>Modern Java applications can use the <strong>Path</strong> and <strong>Paths</strong> classes to construct file paths.</p>

<pre><code>import java.nio.file.Path;

import java.nio.file.Paths;

 

Path filePath = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        "resume.pdf"

);

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath.toString());</code></pre>

<p>This approach is useful for building cleaner and more maintainable test-data paths.</p>

<hr>

<h2>15. File Upload with File Class</h2>

<p>The Java <strong>File</strong> class can also be used to work with file paths.</p>

<pre><code>import java.io.File;

 

File file = new File(

        "test-data/resume.pdf"

);

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(file.getAbsolutePath());</code></pre>

<p>This approach converts a project-relative path into an absolute path before passing it to Selenium.</p>

<hr>

<h2>16. Verifying File Existence Before Upload</h2>

<p>Before uploading a file, it is useful to verify that the file actually exists.</p>

<pre><code>import java.io.File;

 

File file = new File("test-data/resume.pdf");

 

if (!file.exists()) {

    throw new RuntimeException(

        "File not found: " + file.getAbsolutePath()

    );

}

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(file.getAbsolutePath());</code></pre>

<p>This prevents confusing Selenium failures caused by incorrect test-data paths.</p>

<hr>

<h2>17. Verifying That the Path Represents a File</h2>

<p>A path may exist but point to a directory instead of a file. Therefore, a framework can verify both existence and file type.</p>

<pre><code>File file = new File("test-data/resume.pdf");

 

if (!file.exists() || !file.isFile()) {

    throw new RuntimeException(

        "Invalid upload file: " + file.getAbsolutePath()

    );

}

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(file.getAbsolutePath());</code></pre>

<hr>

<h2>18. Uploading an Image</h2>

<p>Image upload is common in profile, product, social media, and content management applications.</p>

<pre><code>String imagePath =

        System.getProperty("user.dir")

        + "\\test-data\\profile.png";

 

driver.findElement(By.id("profileImage"))

        .sendKeys(imagePath);

 

driver.findElement(By.id("saveButton"))

        .click();</code></pre>

<hr>

<h2>19. Uploading a PDF</h2>

<p>PDF files are frequently uploaded for resumes, invoices, certificates, reports, and supporting documents.</p>

<pre><code>String pdfPath =

        System.getProperty("user.dir")

        + "\\test-data\\document.pdf";

 

driver.findElement(By.id("document"))

        .sendKeys(pdfPath);

 

driver.findElement(By.id("upload"))

        .click();</code></pre>

<hr>

<h2>20. Uploading an Excel File</h2>

<p>Applications that support bulk data imports may allow users to upload Excel files.</p>

<pre><code>String excelPath =

        System.getProperty("user.dir")

        + "\\test-data\\users.xlsx";

 

driver.findElement(By.id("excelUpload"))

        .sendKeys(excelPath);

 

driver.findElement(By.id("importButton"))

        .click();</code></pre>

<hr>

<h2>21. Uploading a CSV File</h2>

<p>CSV files are commonly used for bulk data import and migration testing.</p>

<pre><code>String csvPath =

        System.getProperty("user.dir")

        + "\\test-data\\users.csv";

 

driver.findElement(By.id("csvUpload"))

        .sendKeys(csvPath);

 

driver.findElement(By.id("uploadButton"))

        .click();</code></pre>

<hr>

<h2>22. Uploading Multiple Files</h2>

<p>If an application supports multiple file selection through a single file input, Selenium can provide multiple paths separated by newline characters.</p>

<pre><code>String file1 =

        System.getProperty("user.dir")

        + "\\test-data\\document1.pdf";

 

String file2 =

        System.getProperty("user.dir")

        + "\\test-data\\document2.pdf";

 

String files = file1 + "\n" + file2;

 

driver.findElement(By.id("documents"))

        .sendKeys(files);</code></pre>

<p>This technique depends on the application's file input supporting multiple file selection.</p>

<hr>

<h2>23. HTML Multiple File Upload</h2>

<p>An HTML multiple upload control may look like this:</p>

<pre><code>&lt;input type="file" id="documents" multiple&gt;</code></pre>

<p>The <strong>multiple</strong> attribute allows the control to accept more than one file.</p>

<hr>

<h2>24. Verifying Multiple File Selection</h2>

<p>After selecting multiple files, the application may display the selected file names. Selenium can verify the displayed information.</p>

<pre><code>String expectedFile = "document1.pdf";

 

String uploadedFileName =

        driver.findElement(

            By.id("selectedFileName")

        ).getText();

 

Assert.assertTrue(

        uploadedFileName.contains(expectedFile)

);</code></pre>

<hr>

<h2>25. File Upload with TestNG</h2>

<p>File upload can be integrated with TestNG to create structured automated tests.</p>

<pre><code>import java.io.File;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class FileUploadTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.get("https://example.com/upload");

    }

 

    @Test

    public void uploadFileTest() {

 

        File file =

                new File("test-data/resume.pdf");

 

        driver.findElement(By.id("fileUpload"))

                .sendKeys(file.getAbsolutePath());

 

        driver.findElement(By.id("uploadButton"))

                .click();

 

        String message =

                driver.findElement(By.id("successMessage"))

                        .getText();

 

        Assert.assertTrue(

                message.contains("success")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>26. File Upload with Page Object Model</h2>

<p>File upload can be separated into a Page Object method while the test class remains responsible for test execution and validation.</p>

<pre><code>public class UploadPage {

 

    WebDriver driver;

 

    By fileInput = By.id("fileUpload");

    By uploadButton = By.id("uploadButton");

    By successMessage = By.id("successMessage");

 

    public UploadPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void uploadFile(String filePath) {

        driver.findElement(fileInput)

                .sendKeys(filePath);

    }

 

    public void clickUpload() {

        driver.findElement(uploadButton)

                .click();

    }

 

    public String getSuccessMessage() {

        return driver.findElement(successMessage)

                .getText();

    }

}</code></pre>

<hr>

<h2>27. POM Test Class for File Upload</h2>

<pre><code>public class UploadTest {

 

    WebDriver driver;

    UploadPage uploadPage;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.get("https://example.com/upload");

        uploadPage = new UploadPage(driver);

    }

 

    @Test

    public void uploadTest() {

 

        String filePath =

                System.getProperty("user.dir")

                + "\\test-data\\resume.pdf";

 

        uploadPage.uploadFile(filePath);

        uploadPage.clickUpload();

 

        Assert.assertTrue(

                uploadPage.getSuccessMessage()

                        .contains("success")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        driver.quit();

    }

}</code></pre>

<hr>

<h2>28. File Upload Using Data Provider</h2>

<p>TestNG Data Providers can be used to test multiple files with the same upload workflow.</p>

<pre><code>@DataProvider(name = "files")

public Object[][] files() {

    return new Object[][] {

        {"test-data/resume.pdf"},

        {"test-data/profile.png"},

        {"test-data/document.pdf"}

    };

}

 

@Test(dataProvider = "files")

public void uploadTest(String filePath) {

 

    File file = new File(filePath);

 

    driver.findElement(By.id("fileUpload"))

            .sendKeys(file.getAbsolutePath());

 

    driver.findElement(By.id("uploadButton"))

            .click();

}</code></pre>

<hr>

<h2>29. File Upload with Expected Results</h2>

<p>A Data Provider can supply both the file path and expected result.</p>

<pre><code>@DataProvider(name = "uploadData")

public Object[][] uploadData() {

    return new Object[][] {

        {"test-data/resume.pdf", "success"},

        {"test-data/image.png", "success"},

        {"test-data/document.txt", "invalid"}

    };

}

 

@Test(dataProvider = "uploadData")

public void uploadValidationTest(

        String filePath,

        String expectedResult) {

 

    File file = new File(filePath);

 

    driver.findElement(By.id("fileUpload"))

            .sendKeys(file.getAbsolutePath());

 

    driver.findElement(By.id("uploadButton"))

            .click();

 

    String actualResult =

            driver.findElement(By.id("message"))

                    .getText();

 

    Assert.assertTrue(

            actualResult.toLowerCase()

                    .contains(expectedResult)

    );

}</code></pre>

<hr>

<h2>30. File Type Validation</h2>

<p>Many applications restrict uploads to specific file types. For example, a resume portal may allow PDF and DOCX files but reject executable files.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>File Type</th><th>Example</th><th>Possible Validation</th></tr>

<tr><td>PDF</td><td>resume.pdf</td><td>Allowed</td></tr>

<tr><td>DOCX</td><td>resume.docx</td><td>Allowed</td></tr>

<tr><td>PNG</td><td>profile.png</td><td>Allowed for image upload</td></tr>

<tr><td>JPG</td><td>photo.jpg</td><td>Allowed for image upload</td></tr>

<tr><td>TXT</td><td>notes.txt</td><td>May be rejected</td></tr>

<tr><td>EXE</td><td>program.exe</td><td>Usually restricted</td></tr>

</table>

<hr>

<h2>31. Testing Invalid File Types</h2>

<p>Negative testing should verify that unsupported file types are rejected correctly.</p>

<pre><code>String invalidFile =

        System.getProperty("user.dir")

        + "\\test-data\\invalid.exe";

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(invalidFile);

 

driver.findElement(By.id("uploadButton"))

        .click();

 

String error =

        driver.findElement(By.id("errorMessage"))

                .getText();

 

Assert.assertTrue(

        error.contains("file type")

);</code></pre>

<hr>

<h2>32. Testing File Size Validation</h2>

<p>Applications may impose maximum file-size restrictions.</p>

<p>For example, a website may allow files up to a specific configured size.</p>

<pre><code>File file = new File(

        "test-data/large-file.pdf"

);

 

System.out.println(

        "File size: " + file.length()

);</code></pre>

<p>The test can then upload the file and verify that the application displays the appropriate validation message.</p>

<hr>

<h2>33. Testing Empty File Upload</h2>

<p>A file upload field may be mandatory. A test should verify the behavior when the user clicks the upload or submit button without selecting a file.</p>

<pre><code>driver.findElement(By.id("uploadButton"))

        .click();

 

String error =

        driver.findElement(By.id("errorMessage"))

                .getText();

 

Assert.assertTrue(

        error.contains("required")

);</code></pre>

<hr>

<h2>34. Testing File Name Validation</h2>

<p>Some applications validate file names or file extensions. Test cases can include valid and invalid file names.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Case</th><th>File Name</th><th>Expected Result</th></tr>

<tr><td>Valid PDF</td><td>resume.pdf</td><td>Accepted</td></tr>

<tr><td>Valid DOCX</td><td>resume.docx</td><td>Accepted</td></tr>

<tr><td>Wrong Extension</td><td>resume.exe</td><td>Rejected</td></tr>

<tr><td>Empty Name</td><td>file without valid name</td><td>Validation</td></tr>

<tr><td>Long Name</td><td>Very long file name</td><td>Application-specific validation</td></tr>

</table>

<hr>

<h2>35. Handling File Upload Success Messages</h2>

<p>After uploading a file, the application may display a success message.</p>

<pre><code>String message =

        driver.findElement(

            By.id("successMessage")

        ).getText();

 

Assert.assertTrue(

        message.contains("File uploaded")

);</code></pre>

<hr>

<h2>36. Handling File Upload Error Messages</h2>

<p>Invalid files should normally produce an error or validation message.</p>

<pre><code>String errorMessage =

        driver.findElement(

            By.id("errorMessage")

        ).getText();

 

Assert.assertTrue(

        errorMessage.contains("Invalid file")

);</code></pre>

<hr>

<h2>37. Waiting for Upload Completion</h2>

<p>File upload may involve server-side processing. In such situations, an explicit wait can be used to wait for a success message or another upload-completion indicator.</p>

<pre><code>WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

WebElement message =

        wait.until(

            ExpectedConditions.visibilityOfElementLocated(

                By.id("successMessage")

            )

        );

 

Assert.assertTrue(

        message.isDisplayed()

);</code></pre>

<hr>

<h2>38. Waiting for Upload Button</h2>

<p>If the upload button becomes available after file selection, Selenium can wait for it to become clickable.</p>

<pre><code>WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

WebElement uploadButton =

        wait.until(

            ExpectedConditions.elementToBeClickable(

                By.id("uploadButton")

            )

        );

 

uploadButton.click();</code></pre>

<hr>

<h2>39. File Upload with Hidden Input</h2>

<p>Some modern web applications hide the native file input and display a custom upload button.</p>

<p>For example:</p>

<pre><code>&lt;button id="chooseFile"&gt;Upload File&lt;/button&gt;

&lt;input type="file" id="fileInput" style="display:none"&gt;</code></pre>

<p>The visible button may trigger the hidden file input through JavaScript.</p>

<p>When possible, the automation should interact with the actual file input rather than attempting to automate the operating-system file dialog.</p>

<hr>

<h2>40. Why sendKeys() is Preferred for File Input</h2>

<p>When the application exposes a standard HTML file input, <strong>sendKeys()</strong> is generally simpler and more reliable than automating the operating-system file-selection window.</p>

<ul>

<li>It works directly with the HTML file input.</li>

<li>It avoids OS-specific file-dialog interactions.</li>

<li>It is easier to integrate into CI environments.</li>

<li>It is suitable for automated test frameworks.</li>

<li>It keeps the automation logic inside Selenium.</li>

</ul>

<hr>

<h2>41. Native File Dialog Problem</h2>

<p>A common misconception is that Selenium directly controls every operating-system window. Selenium primarily automates the browser and web page.</p>

<p>A native file chooser can appear when a user clicks a file-upload control. Instead of trying to control that dialog, the preferred Selenium approach for a standard file input is usually:</p>

<pre><code>driver.findElement(By.id("fileInput"))

        .sendKeys(filePath);</code></pre>

<hr>

<h2>42. Selenium File Upload vs OS File Dialog</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Approach</th><th>Description</th></tr>

<tr><td>sendKeys()</td><td>Provides a file path directly to an HTML file input.</td></tr>

<tr><td>OS Automation</td><td>Automates the native operating-system file chooser.</td></tr>

<tr><td>JavaScript</td><td>May be used for special application behavior, but should not be used to bypass application security.</td></tr>

</table>

<p>For a standard Selenium file input, <strong>sendKeys()</strong> is normally the simplest approach.</p>

<hr>

<h2>43. File Upload with JavaScript-Triggered Input</h2>

<p>Some applications use JavaScript to trigger the file input when the user clicks a custom button.</p>

<p>The automation should identify the underlying file input in the DOM and use it where possible.</p>

<pre><code>WebElement fileInput =

        driver.findElement(

            By.cssSelector("input[type='file']")

        );

 

fileInput.sendKeys(

        new File("test-data/document.pdf")

                .getAbsolutePath()

);</code></pre>

<hr>

<h2>44. Handling Multiple Upload Controls</h2>

<p>If a page contains several upload controls, a generic locator such as <strong>input[type='file']</strong> may return multiple elements.</p>

<p>Use a specific locator.</p>

<pre><code>driver.findElement(

        By.id("resumeUpload")

).sendKeys(

        new File("test-data/resume.pdf")

                .getAbsolutePath()

);

 

driver.findElement(

        By.id("profileUpload")

).sendKeys(

        new File("test-data/profile.png")

                .getAbsolutePath()

);</code></pre>

<hr>

<h2>45. File Upload Using WebElement</h2>

<p>Storing the upload element in a WebElement variable can make the code easier to read.</p>

<pre><code>WebElement fileInput =

        driver.findElement(By.id("fileUpload"));

 

String filePath =

        new File("test-data/document.pdf")

                .getAbsolutePath();

 

fileInput.sendKeys(filePath);</code></pre>

<hr>

<h2>46. Creating a Reusable Upload Utility</h2>

<p>Large Selenium frameworks can create reusable utility methods for file uploads.</p>

<pre><code>public class FileUploadUtil {

 

    public static void uploadFile(

            WebDriver driver,

            By locator,

            String filePath) {

 

        File file = new File(filePath);

 

        if (!file.exists()) {

            throw new RuntimeException(

                "File not found: "

                + file.getAbsolutePath()

            );

        }

 

        driver.findElement(locator)

                .sendKeys(file.getAbsolutePath());

    }

}</code></pre>

<p>The utility can then be reused across multiple tests.</p>

<hr>

<h2>47. Using the File Upload Utility</h2>

<pre><code>FileUploadUtil.uploadFile(

        driver,

        By.id("fileUpload"),

        "test-data/resume.pdf"

);

 

driver.findElement(By.id("uploadButton"))

        .click();</code></pre>

<hr>

<h2>48. File Upload Utility with Path</h2>

<pre><code>public static String getFilePath(String fileName) {

 

    return Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        fileName

    ).toString();

}</code></pre>

<p>Usage:</p>

<pre><code>String path =

        FileUploadUtil.getFilePath("resume.pdf");

 

driver.findElement(By.id("fileUpload"))

        .sendKeys(path);</code></pre>

<hr>

<h2>49. File Upload and Page Object Model Architecture</h2>

<pre><code>Test Class

    |

    v

Page Object

    |

    v

Upload Method

    |

    v

File Path Utility

    |

    v

Local Test Data

    |

    v

HTML File Input

    |

    v

Upload Button

    |

    v

Application

    |

    v

Validation / Assertion</code></pre>

<hr>

<h2>50. File Upload Project Structure</h2>

<pre><code>src

|-- test

|   |-- java

|   |   |-- tests

|   |   |   |-- FileUploadTest.java

|   |   |

|   |   |-- pages

|   |   |   |-- UploadPage.java

|   |   |

|   |   |-- utilities

|   |       |-- FileUploadUtil.java

|   |       |-- DriverFactory.java

|   |

|-- test-data

|   |-- resume.pdf

|   |-- profile.png

|   |-- document.pdf

|   |-- users.csv

|   |-- users.xlsx

|   |

|-- pom.xml</code></pre>

<hr>

<h2>51. File Upload with External Test Data</h2>

<p>File names can be stored separately from test logic and passed into the test through a Data Provider or configuration mechanism.</p>

<pre><code>@DataProvider(name = "uploadFiles")

public Object[][] uploadFiles() {

    return new Object[][] {

        {"resume.pdf"},

        {"profile.png"},

        {"document.pdf"}

    };

}

 

@Test(dataProvider = "uploadFiles")

public void uploadTest(String fileName) {

 

    String filePath = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        fileName

    ).toString();

 

    driver.findElement(By.id("fileUpload"))

            .sendKeys(filePath);

}</code></pre>

<hr>

<h2>52. File Upload Test Scenarios</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Scenario</th><th>Expected Result</th></tr>

<tr><td>Valid PDF</td><td>File uploaded successfully</td></tr>

<tr><td>Valid image</td><td>Image uploaded successfully</td></tr>

<tr><td>Unsupported extension</td><td>Validation error</td></tr>

<tr><td>Large file</td><td>Size validation message</td></tr>

<tr><td>No file selected</td><td>Required-field validation</td></tr>

<tr><td>Multiple files</td><td>Files accepted when supported</td></tr>

<tr><td>Duplicate file</td><td>Application-specific behavior</td></tr>

<tr><td>Invalid file name</td><td>Validation message when applicable</td></tr>

</table>

<hr>

<h2>53. Positive File Upload Testing</h2>

<p>Positive test cases verify that supported files can be uploaded successfully.</p>

<ul>

<li>Upload a valid PDF.</li>

<li>Upload a valid PNG image.</li>

<li>Upload a valid JPG image.</li>

<li>Upload a valid DOCX document.</li>

<li>Upload a file within the allowed size.</li>

<li>Upload multiple files when supported.</li>

<li>Verify the success message.</li>

<li>Verify the uploaded file name.</li>

</ul>

<hr>

<h2>54. Negative File Upload Testing</h2>

<p>Negative test cases verify that invalid uploads are handled correctly.</p>

<ul>

<li>Upload an unsupported file type.</li>

<li>Upload an oversized file.</li>

<li>Submit without selecting a file.</li>

<li>Use an invalid file name.</li>

<li>Use a corrupted test file when appropriate.</li>

<li>Verify the correct validation message.</li>

<li>Verify that invalid files are not accepted as successful uploads.</li>

</ul>

<hr>

<h2>55. File Upload Validation Matrix</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Input</th><th>Expected Behavior</th></tr>

<tr><td>resume.pdf</td><td>Accepted</td></tr>

<tr><td>resume.docx</td><td>Accepted if DOCX is supported</td></tr>

<tr><td>photo.png</td><td>Accepted for image upload</td></tr>

<tr><td>script.exe</td><td>Rejected</td></tr>

<tr><td>very-large.pdf</td><td>Rejected if above size limit</td></tr>

<tr><td>No file</td><td>Required validation</td></tr>

</table>

<hr>

<h2>56. File Upload and Security Testing</h2>

<p>File upload functionality can introduce security risks if the application does not validate uploaded content correctly. Automation tests can verify expected application-side validation behavior.</p>

<p>Typical validation areas include:</p>

<ul>

<li>Allowed file extensions.</li>

<li>Maximum file size.</li>

<li>Required file validation.</li>

<li>File-name validation.</li>

<li>Duplicate-file handling.</li>

<li>Application response to malformed test files.</li>

<li>Authentication and authorization requirements.</li>

</ul>

<p>Security testing should be performed according to the application's authorized testing scope and security requirements.</p>

<hr>

<h2>57. File Upload in CI/CD</h2>

<p>File upload tests should work reliably in CI/CD environments. Test files should preferably be maintained as project test data or retrieved through an approved test-data mechanism rather than relying on a developer's personal desktop path.</p>

<pre><code>Developer Commit

       |

       v

CI/CD Pipeline

       |

       v

Build

       |

       v

TestNG

       |

       v

File Upload Test

       |

       v

Test Data

       |

       v

Selenium WebDriver

       |

       v

Application

       |

       v

Assertions

       |

       v

Test Report</code></pre>

<hr>

<h2>58. Avoiding Machine-Specific Paths</h2>

<p>Avoid hard-coded paths such as:</p>

<pre><code>C:\Users\John\Desktop\resume.pdf</code></pre>

<p>Instead, use project-relative or dynamically constructed paths.</p>

<pre><code>String filePath = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        "resume.pdf"

).toString();</code></pre>

<p>This makes the test easier to execute on different development and CI machines.</p>

<hr>

<h2>59. Cross-Platform File Paths</h2>

<p>Using <strong>Paths.get()</strong> is useful when a framework needs to run on different operating systems.</p>

<pre><code>Path path = Paths.get(

        System.getProperty("user.dir"),

        "test-data",

        "resume.pdf"

);

 

String filePath = path.toString();</code></pre>

<p>This avoids manually constructing operating-system-specific separators.</p>

<hr>

<h2>60. File Upload with Assertions</h2>

<p>Uploading the file is only one part of the test. The test should verify that the application processed the file correctly.</p>

<pre><code>driver.findElement(By.id("fileUpload"))

        .sendKeys(filePath);

 

driver.findElement(By.id("uploadButton"))

        .click();

 

WebElement successMessage =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        ).until(

            ExpectedConditions.visibilityOfElementLocated(

                By.id("successMessage")

            )

        );

 

Assert.assertTrue(

        successMessage.getText()

                .contains("uploaded")

);</code></pre>

<hr>

<h2>61. File Upload and Test Reports</h2>

<p>File upload tests should provide useful information in automation reports. When a test fails, the report should make it possible to identify the file and scenario being tested without exposing sensitive information.</p>

<pre><code>Test Case: Resume Upload

File: resume.pdf

Expected: Upload Successful

Actual: Upload Successful

Status: PASS</code></pre>

<p>For failures, useful information may include the test scenario, file name, validation message, and screenshot or browser evidence where the framework supports it.</p>

<hr>

<h2>62. Common Mistakes in File Upload</h2>

<ul>

<li>Using an incorrect file path.</li>

<li>Using a file that does not exist.</li>

<li>Using the wrong locator.</li>

<li>Trying to use sendKeys() on a non-file element.</li>

<li>Assuming every custom upload button is itself an input element.</li>

<li>Ignoring hidden or dynamically generated file inputs.</li>

<li>Using machine-specific paths.</li>

<li>Not verifying the uploaded result.</li>

<li>Not waiting for asynchronous upload completion.</li>

<li>Sharing mutable test files across parallel tests without proper isolation.</li>

<li>Hard-coding test data in multiple test classes.</li>

<li>Not testing invalid file types and file-size boundaries.</li>

</ul>

<hr>

<h2>63. Common Error: File Not Found</h2>

<p>If the specified path does not point to a real file, the upload test will fail.</p>

<p>Use Java file validation before calling sendKeys().</p>

<pre><code>File file = new File(filePath);

 

if (!file.exists()) {

    throw new RuntimeException(

        "File does not exist: "

        + file.getAbsolutePath()

    );

}</code></pre>

<hr>

<h2>64. Common Error: Wrong Locator</h2>

<p>If the locator points to a button, label, or another element instead of the actual file input, the upload operation may fail.</p>

<p>Inspect the HTML and identify:</p>

<pre><code>&lt;input type="file"&gt;</code></pre>

<p>Then locate that element.</p>

<pre><code>driver.findElement(

        By.cssSelector("input[type='file']")

).sendKeys(filePath);</code></pre>

<hr>

<h2>65. Common Error: File Input Not Present</h2>

<p>Some applications create the file input dynamically only after a user interaction. In such cases, the automation may need to trigger the appropriate page action and then locate the input.</p>

<pre><code>driver.findElement(By.id("chooseFile"))

        .click();

 

WebElement fileInput =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        ).until(

            ExpectedConditions.presenceOfElementLocated(

                By.cssSelector("input[type='file']")

            )

        );

 

fileInput.sendKeys(filePath);</code></pre>

<hr>

<h2>66. Common Error: Upload Completion Not Verified</h2>

<p>A test should not assume that selecting a file means the server successfully received it.</p>

<p>A complete test should generally validate an application-specific result such as:</p>

<ul>

<li>Success message.</li>

<li>Uploaded file name.</li>

<li>Preview.</li>

<li>Updated record.</li>

<li>Downloadable uploaded document.</li>

<li>Changed application state.</li>

</ul>

<hr>

<h2>67. Best Practices for File Upload Automation</h2>

<ul>

<li>Prefer sendKeys() for standard HTML file inputs.</li>

<li>Keep test files inside a dedicated test-data directory.</li>

<li>Use relative or dynamically constructed paths.</li>

<li>Validate that files exist before uploading.</li>

<li>Use Page Object Model for application interaction logic.</li>

<li>Create reusable file-upload utilities.</li>

<li>Use Data Providers for multiple upload scenarios.</li>

<li>Test both valid and invalid files.</li>

<li>Validate file-size restrictions.</li>

<li>Validate file-type restrictions.</li>

<li>Use explicit waits for asynchronous upload completion.</li>

<li>Do not expose passwords, tokens, or other secrets in uploaded test data.</li>

<li>Ensure test files are available in CI/CD environments.</li>

<li>Keep parallel tests isolated when they modify uploaded files.</li>

<li>Capture useful failure information in reports.</li>

</ul>

<hr>

<h2>68. File Upload Framework Architecture</h2>

<pre><code>                Test Class

                    |

                    v

             Data Provider

                    |

                    v

             Upload Page

                    |

                    v

          File Upload Utility

                    |

                    v

              Test Data

                    |

                    v

             File Input

                    |

                    v

            Upload Button

                    |

                    v

              Application

                    |

                    v

               Assertion

                    |

                    v

                Report</code></pre>

<hr>

<h2>69. Complete Practical File Upload Example</h2>

<pre><code>import java.io.File;

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class FileUploadTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage().window().maximize();

 

        driver.get(

            "https://example.com/upload"

        );

    }

 

    @DataProvider(name = "uploadData")

    public Object[][] uploadData() {

 

        return new Object[][] {

            {"resume.pdf"},

            {"document.pdf"},

            {"profile.png"}

        };

    }

 

    @Test(dataProvider = "uploadData")

    public void uploadFileTest(String fileName) {

 

        String filePath = new File(

            "test-data/" + fileName

        ).getAbsolutePath();

 

        File file = new File(filePath);

 

        Assert.assertTrue(

            file.exists(),

            "File not found: " + filePath

        );

 

        driver.findElement(

            By.id("fileUpload")

        ).sendKeys(filePath);

 

        driver.findElement(

            By.id("uploadButton")

        ).click();

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

            );

 

        String message =

            wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("successMessage")

                )

            ).getText();

 

        Assert.assertTrue(

            message.toLowerCase()

                   .contains("uploaded")

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>70. Practical File Upload Project</h2>

<p>Consider a job portal that allows users to upload resumes.</p>

<p>The automation framework can validate the complete workflow:</p>

<pre><code>Open Job Portal

      |

      v

Login

      |

      v

Open Profile

      |

      v

Select Resume Upload

      |

      v

Locate File Input

      |

      v

Upload resume.pdf

      |

      v

Click Save

      |

      v

Wait for Upload

      |

      v

Verify Success Message

      |

      v

Verify Resume Name

      |

      v

Generate Test Report</code></pre>

<p>Additional negative scenarios can include unsupported file types, oversized files, missing files, and invalid file names.</p>

<hr>

<h2>71. Real-World File Upload Test Cases</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Test Case</th><th>Input</th><th>Expected Result</th></tr>

<tr><td>Valid Resume</td><td>resume.pdf</td><td>Upload successful</td></tr>

<tr><td>Valid Document</td><td>document.docx</td><td>Upload successful if supported</td></tr>

<tr><td>Valid Image</td><td>profile.png</td><td>Upload successful</td></tr>

<tr><td>Invalid Extension</td><td>program.exe</td><td>Validation error</td></tr>

<tr><td>Large File</td><td>large.pdf</td><td>Size validation</td></tr>

<tr><td>No File</td><td>No selection</td><td>Required validation</td></tr>

<tr><td>Multiple Files</td><td>Several supported files</td><td>Accepted when supported</td></tr>

<tr><td>Incorrect File Name</td><td>Invalid naming scenario</td><td>Validation when applicable</td></tr>

<tr><td>Upload Failure</td><td>Test failure condition</td><td>Correct error displayed</td></tr>

</table>

<hr>

<h2>72. File Upload vs File Download</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>File Upload</th><th>File Download</th></tr>

<tr><td>Direction</td><td>Local system to application</td><td>Application to local system</td></tr>

<tr><td>Common Element</td><td>input type="file"</td><td>Download link/button</td></tr>

<tr><td>Typical Selenium Action</td><td>sendKeys(filePath)</td><td>Click download element</td></tr>

<tr><td>Validation</td><td>Uploaded file/result</td><td>Downloaded file existence/content</td></tr>

</table>

<hr>

<h2>73. File Upload vs sendKeys for Text Input</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Aspect</th><th>Text Input</th><th>File Input</th></tr>

<tr><td>Purpose</td><td>Enter text</td><td>Select file for upload</td></tr>

<tr><td>Method</td><td>sendKeys("text")</td><td>sendKeys("file path")</td></tr>

<tr><td>Example</td><td>Username</td><td>resume.pdf</td></tr>

<tr><td>Validation</td><td>Entered text</td><td>Uploaded file/result</td></tr>

</table>

<hr>

<h2>74. Quick Revision</h2>

<ul>

<li>File upload is commonly automated using the HTML file input.</li>

<li>The standard Selenium technique is sendKeys().</li>

<li>Provide the complete file path to sendKeys().</li>

<li>Use File or Path to construct reliable paths.</li>

<li>System.getProperty("user.dir") can help create project-relative paths.</li>

<li>Always verify that the test file exists.</li>

<li>Use POM to keep upload interactions maintainable.</li>

<li>Use Data Providers for multiple files or upload scenarios.</li>

<li>Use explicit waits when upload completion is asynchronous.</li>

<li>Validate both positive and negative file-upload scenarios.</li>

<li>Avoid machine-specific file paths.</li>

<li>Make test files available in CI/CD environments.</li>

<li>Verify the actual application result after upload.</li>

</ul>

<hr>

<h2>75. Interview Questions on File Upload</h2>

<h3>1. How do you upload a file using Selenium?</h3>

<p>For a standard HTML file input, locate the input element and use <strong>sendKeys()</strong> with the file path.</p>

<h3>2. Which HTML element is commonly used for file upload?</h3>

<p>The standard element is <strong>&lt;input type="file"&gt;</strong>.</p>

<h3>3. Can Selenium handle a file upload without opening the native file dialog?</h3>

<p>Yes. When a standard file input is available, sendKeys() can provide the file path directly to the element.</p>

<h3>4. Why is sendKeys() used for file upload?</h3>

<p>It allows Selenium to provide the local file path directly to the HTML file input.</p>

<h3>5. Can XPath be used for file upload?</h3>

<p>Yes. XPath can locate an input element with type="file".</p>

<h3>6. Can CSS selectors be used for file upload?</h3>

<p>Yes. For example, <strong>input[type='file']</strong> can locate a standard file input.</p>

<h3>7. How can you create a portable file path?</h3>

<p>Use project-relative paths, System.getProperty("user.dir"), or Java Path APIs instead of hard-coded personal computer paths.</p>

<h3>8. How do you verify that the file exists?</h3>

<p>Use Java's File or Path APIs before passing the path to Selenium.</p>

<h3>9. Can Selenium upload multiple files?</h3>

<p>Yes, when the application supports multiple selection. Multiple paths can be supplied to the file input using newline-separated paths.</p>

<h3>10. How do you test an invalid file type?</h3>

<p>Upload a controlled test file with an unsupported extension and verify that the application displays the expected validation.</p>

<h3>11. How do you test file-size validation?</h3>

<p>Use test files representing valid and oversized conditions and verify the application's response.</p>

<h3>12. Can File Upload be integrated with TestNG?</h3>

<p>Yes. File upload tests can use TestNG annotations, assertions, Data Providers, configuration methods, and reports.</p>

<h3>13. Can File Upload be implemented using Page Object Model?</h3>

<p>Yes. The upload locator and upload actions can be encapsulated inside a Page Object.</p>

<h3>14. How do you handle a hidden file input?</h3>

<p>When possible, locate the underlying HTML file input and provide the file path directly rather than automating the operating-system file dialog.</p>

<h3>15. Why should hard-coded local paths be avoided?</h3>

<p>They make tests dependent on one particular machine and can cause failures on other developer machines or CI environments.</p>

<h3>16. How can file upload tests run in CI/CD?</h3>

<p>Keep required test files in the project or an approved test-data source and construct paths dynamically so the files are available in the CI environment.</p>

<h3>17. How do you verify successful file upload?</h3>

<p>Verify an application-specific success message, uploaded file name, preview, updated record, or another reliable result.</p>

<h3>18. Can Data Providers be used for file upload?</h3>

<p>Yes. A Data Provider can provide multiple file names, paths, expected results, or upload scenarios.</p>

<h3>19. What are common file-upload mistakes?</h3>

<p>Incorrect file paths, wrong locators, missing files, unsupported file types, failure to wait for upload completion, and failure to verify the result are common mistakes.</p>

<h3>20. What is the preferred approach for a standard HTML file input?</h3>

<p>Locate the file input and use <strong>sendKeys()</strong> with the appropriate file path.</p>

<hr>

<h2>76. Learning Roadmap for File Upload</h2>

<ol>

<li>Understand HTML file input elements.</li>

<li>Learn Selenium locators.</li>

<li>Learn sendKeys() for file inputs.</li>

<li>Practice absolute file paths.</li>

<li>Practice project-relative file paths.</li>

<li>Learn Java File and Path APIs.</li>

<li>Validate file existence.</li>

<li>Automate PDF and image uploads.</li>

<li>Automate multiple file uploads.</li>

<li>Test invalid file extensions.</li>

<li>Test file-size validation.</li>

<li>Use explicit waits for upload completion.</li>

<li>Integrate file upload with TestNG.</li>

<li>Integrate file upload with Data Providers.</li>

<li>Implement file upload in Page Object Model.</li>

<li>Create reusable file-upload utilities.</li>

<li>Run upload tests in CI/CD.</li>

<li>Integrate upload tests with reporting.</li>

</ol>

<hr>

<h2>77. Summary</h2>

<p>File Upload is an important Selenium WebDriver automation concept used to automate web applications that accept documents, images, spreadsheets, PDFs, and other files.</p>

<p>For a standard HTML <strong>&lt;input type="file"&gt;</strong> element, the most common Selenium approach is to locate the element and use <strong>sendKeys()</strong> with the appropriate file path.</p>

<p>A reliable automation framework should avoid machine-specific paths, verify file existence, organize test files properly, validate upload results, handle asynchronous upload operations, and include both positive and negative test cases.</p>

<p>File upload automation becomes more maintainable when combined with <strong>TestNG, Data Providers, Page Object Model, reusable utilities, assertions, explicit waits, and reporting</strong>.</p>

<p><strong>Final Takeaway:</strong> A robust Selenium file-upload test does more than select a file. It validates the complete upload workflow, including file selection, file-type and size validation, upload processing, success or error messages, and the final application state.</p>

<hr>

<h2>78. Course Resources</h2>

<p>Learn more about Selenium automation testing and related framework concepts:</p>

<ul>

<li><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a></li>

<li><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Selenium Course Demo</a></li>

</ul>

</div>

Previous Next
whatsapp